<template>
  <div>
    <div class="bank"></div>
    <el-card header="语音内容">
      <el-input
        id="word"
        type="textarea"
        placeholder="请输入文本"
        v-model="word"
        maxlength="300"
        rows="4"
        show-word-limit
      >
      </el-input>
      <div class="bank"></div>
      <el-card>
        <el-button @click="changeToAudio" type="primary">转为语音</el-button>
      </el-card>
      <div class="bank"></div>
      <el-card>
        <el-button @click="pause" type="warning">暂停</el-button>
        <el-button @click="resume" type="success">继续</el-button>
        <el-button @click="cancel" type="info">取消</el-button>
      </el-card>
      <div class="bank"></div>
    </el-card>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';

const router=useRouter()
export default defineComponent({
  name: "WordToAudio",
  props:['textWord'],
  created(){
    this.word = this.textWord
  },
  setup() {
    const word = ref<string>("");
    const isPaused = ref<boolean>(false); // 判断是否暂停

    const changeToAudio = () => {
      if (!word.value) {
        ElMessage({ message: "请输入文本", type: "warning" });
        return;
      }

      if (isPaused.value) {
       
        ElMessage({ message: "当前语音已暂停,请点击继续!", type: "warning" });
        return;
      } else if (window.speechSynthesis.speaking) {
       
        ElMessage({ message: "当前已有正在播放的语音!", type: "warning" });
        return;
      }
      // 为了防止在暂停状态下转语音，调用前设置继续播放
      window.speechSynthesis.resume();
      // 设置播放
      const textArea = document.getElementById('word') as HTMLTextAreaElement;
      const range = document.createRange();
      range.selectNodeContents(textArea);
      const speech = new SpeechSynthesisUtterance();
      speech.text = word.value; // 内容
      speech.lang = "zh-cn"; // 语言
      speech.voiceURI = "Microsoft Huihui - Chinese (Simplified, PRC)"; // 声音和服务
      speech.volume = 0.7; // 音量
      speech.rate = 1; // 语速
      speech.pitch = 1; // 音高
      window.speechSynthesis.speak(speech);
      const highlight = document.createElement('span');
      highlight.style.backgroundColor = 'red';
      range.surroundContents(highlight);
    };

    const pause = () => {
      isPaused.value = true;
      window.speechSynthesis.pause();
    };

    const resume = () => {
      isPaused.value = false;
      window.speechSynthesis.resume();
    };

    const cancel = () => {
      window.speechSynthesis.cancel();
    };

    const getvoice = () => {
      console.log(window.speechSynthesis.getVoices());
    };

    const goBack = () => {
      // 假设使用的是 Vue Router
     
     router.push({ path: "/entry" });
    };

    return {
      word,
      isPaused,
      changeToAudio,
      pause,
      resume,
      cancel,
      getvoice,
      goBack,
    };
  },
});
</script>

<style scoped>
.bank {
  padding: 10px;
}
</style>
